<?php
namespace app\controller;

use think\facade\Filesystem;
use think\response\Json;
use League\Flysystem\Filesystem as LeagueFilesystem;
use Iidestiny\Flysystem\Oss\OssAdapter;
/**
 * 文件上传
 */
class Uploader extends \app\BaseController
{
    /**
     * 文件上传
     * @return Json
     */
    public function index() :Json
    {
        try {
            $file = request()->file('file');
            //格式校验
            $this->validateMimeType($file);
            // 上传到OSS
            $saveName = Filesystem::putFile('upload', $file);
            // 获取完整访问URL
            $result = $this->upload($saveName, $file->getPathname());
            return apiResponse($result['code'], $result['message'], $result['data']);
        } catch (\Exception $e) {
            return apiResponse($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 上传文件至阿里云OSS
     * @param string $saveName 文件保存名称
     * @param string $savePath 文件保存路径
     * @return array
     */
    public function upload(string $saveName,string $savePath): array
    {
        //从配置文件读取参数
        $prefix = env('OSS_PREFIX');
        $accessKeyId = env('OSS_ACCESS_KEY_ID');
        $accessKeySecret = env('OSS_ACCESS_KEY_SECRET');
        $endpoint= env('OSS_ENDPOINT');
        $bucket = env('OSS_BUCKET');
        $isCName = env('OSS_IS_CNAME');
        $ossUrl = env('OSS_URL');

        try {
            // 创建OSSAdapter
            $adapter = new OssAdapter($accessKeyId, $accessKeySecret, $endpoint, $bucket, $isCName, $prefix);
            // 设置CDN域名
            $adapter->setCdnUrl(env($ossUrl));
            // 创建一个League\Flysystem\Filesystem实例
            $flysystem = new LeagueFilesystem($adapter);
            //尝试上传文件
            $flysystem->writeStream($saveName, fopen($savePath, 'r'));
            //组合文件目录尝试删除文件
            $fileDisk = config('filesystem.default');
            $fileDiskRoot = config('filesystem.disks.' . $fileDisk.'.root');
            //重写路径
            $localSavePath= $fileDiskRoot.'/'.$saveName;
            $fileName = str_replace('\\', '/', $saveName);
    
            //删除temp临时文件
            @unlink($savePath);
            //删除上传存储目录文件
            unlink($localSavePath);
            return modelResponse(200,'上传成功',$ossUrl.$fileName);
        }catch (\Exception $e){
            return modelResponse($e->getCode(),$e->getMessage());
        }
    }
    protected function validateMimeType($file)
    {
        $mimeType = $file->getMime();
        $allowedMimes = [
            'image/jpeg',
            'image/jpg',
            'image/png',
            'image/gif',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
            'application/vnd.ms-excel', // .xls
            'application/msword', // .doc
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
            'application/vnd.ms-powerpoint', // .ppt
            'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
            'application/zip', // .zip
            'application/x-rar-compressed', // .rar
            'application/x-tar', // .tar
            'application/gzip', // .gz
            'application/x-gzip', // .tar.gz

        ];
        if (!in_array($mimeType, $allowedMimes)) {
            return new \Exception("上传文件格式不支持");
        }
    }
}